package com.lst.tools.swagger.config;

import com.lst.tools.swagger.properties.Swagger2Properties;
import com.google.common.base.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author: Frank
 * @date: 2019/09/24 13:51
 * @version: V1.0
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Autowired
    private Swagger2Properties swagger2Properties;

    @Bean
    public Docket buildDocket() {
        Predicate<RequestHandler> predicate = RequestHandlerSelectors.basePackage(swagger2Properties.getBasePackage());
        ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInfo())
                .select()
                .apis(predicate);
        if (swagger2Properties.getEnabled()) {
            return apiSelectorBuilder.paths(PathSelectors.any()).build();
        }
        return apiSelectorBuilder.paths(PathSelectors.none()).build();
    }

    @Bean
    public ApiInfo buildApiInfo() {
        return new ApiInfoBuilder()
                .title(swagger2Properties.getTitle())
                .description(swagger2Properties.getDescription())
                .termsOfServiceUrl(swagger2Properties.getTermsOfServiceUrl())
                .version(swagger2Properties.getVersion())
                .build();
    }
}
